# coding : utf-8


""" get latest appkey and secret from nlu_loader api """

import sys
import json
import requests
import cPickle


def _get_request(url):
    try:
       return requests.get(url).content
    except Exception as e:
        print "Error >>> ", e, "exit!"
        sys.exit(1)

def check_appsecret(appkey):
    secret_map = cPickle.load(file(Secret_File))
    if secret_map.has_key(appkey):
        print "%s >> %s" % (appkey, secret_map[appkey])
    else:
        print "no secret for [%s]" % appkey

def get_secret_by_appkey(appkey):
    url = "http://%s/open-service-nlu-loader/\
    service.nlu.sl?method=nlu.loadAppSecrets&isTestEnv=false&appKey=%s" % (NLU_Loader, appkey)
    ret = _get_request(url)
    print ret
    secret_map = json.loads(ret)
    return secret_map[appkey]

def get_latest_secret():
    ''' get from NLU_loader, do full update '''
    url = "http://%s/open-service-nlu-loader/\
    service.nlu.sl?method=nlu.loadAppSecrets&isTestEnv=false" % NLU_Loader
    ret = _get_request(url)
    secret_map = json.loads(ret)
    print "all_appkey_secrets: %d" % len(secret_map)
    fp = file(Secret_File, 'w')
    cPickle.dump(secret_map, fp)
    fp.close()

def manually_update(appkey_secret_map):
    secret_map = cPickle.load(file(Secret_File))
    for appkey, secret in appkey_secret_map.items():
        if not secret_map.has_key(appkey):
            secret_map[appkey] = secret

    fp = file(Secret_File, 'w')
    cPickle.dump(secret_map, fp)
    fp.close()


if __name__ == '__main__':
    Secret_File = "secret.dump"
    # UAT
    # NLU_Loader = '172.18.10.131:8080'

    # PRD
    NLU_Loader = "172.20.7.190:8080"
    #######  Get from nlu-loader ###########
    # get_latest_secret()
    # get_secret_by_appkey(appkey)

    ##################################################
    appkey_secret_map = {
        "eio5u7y3k2lj7dxz6ajrjvrckcv3h4molqzbrfyv" : "2764f57f781ebe08b9b74ac40d9568c5"
    }
    ##################################################  
    manually_update(appkey_secret_map)    
    check_appsecret("eio5u7y3k2lj7dxz6ajrjvrckcv3h4molqzbrfyv")
   
